package com.example.fengshoutong.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.fengshoutong.R;
import com.example.fengshoutong.bean.Message;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息适配器
 */
public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {
    private List<Message> mDataList = new ArrayList<>();

    public MsgAdapter(List<Message> dataList) {
        this.mDataList = dataList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_msg, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Message data = mDataList.get(position);
        // 如果是接受到的消息，则靠左显示，如果是发送的消息，则靠右显示
        if (data.getType() == 0) {
            holder.text_left_msg.setText(data.getMsg());
            holder.text_right_msg.setVisibility(View.GONE);
            holder.text_left_msg.setVisibility(View.VISIBLE);
        } else {
            holder.text_right_msg.setText(data.getMsg());
            holder.text_left_msg.setVisibility(View.GONE);
            holder.text_right_msg.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public int getItemCount() {
        if (mDataList != null) {
            return mDataList.size();
        }
        return 0;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView text_left_msg;
        TextView text_right_msg;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            text_left_msg = itemView.findViewById(R.id.text_left_msg);
            text_right_msg = itemView.findViewById(R.id.text_right_msg);
        }
    }
}
